package com.example.hw_demo.config;

import com.example.hw_demo.interceptor.LoginInterceptor;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * web相关配置
 */
@Configuration
public class MyWebConfig implements WebMvcConfigurer {


    //获取图片请求url
    @Value("${upload.handler}")
    private String handlerImg;

    //获取图片保存位置
    @Value("${upload.filePath}")
    private String filePath;

    /*静态资源映射*/

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //前端发送的请求 images/**)---->filepath(d:/img/xxx.jpg)(后端)
        registry.addResourceHandler(handlerImg)
                .addResourceLocations("file:"+filePath);
    }

    /**
     * 拦截器配置
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new LoginInterceptor())
                //对哪些路劲拦截
                .addPathPatterns("/**")
                //哪些不拦截
                .excludePathPatterns("/user/login")
                .excludePathPatterns("/user/register")
                 .excludePathPatterns("/file/**")
                .excludePathPatterns("/user/aiLogin")
                .excludePathPatterns(handlerImg);
    }

    /**
     * 跨域问题处理
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);

    }
}
